package com.chao.yyks.util;

import com.alibaba.fastjson.JSONObject;
import com.chao.common.util.exception.SysException;

import java.util.HashMap;
import java.util.Map;
import java.security.MessageDigest;

/**
 * 获取驰声鉴权
 */
public class Digest {

    private static final String CONFIG_APPKEY = "172595235000007e"; //chivox appKey
    private static final String CONFIG_SECRETKEY = "68bb5749f42ae1b950c6cc0da5826491"; //chivox secretKey
    private static final String CONFIG_ENCRYPTALGORITHM = "sha1";

    public static JSONObject getVerificationJson() {
        JSONObject retMap = new JSONObject();
        try {
            long timestamp = System.currentTimeMillis();
            String sig = CONFIG_APPKEY + timestamp + CONFIG_SECRETKEY;
            sig = Digest.getDigest(sig, CONFIG_ENCRYPTALGORITHM);
            retMap.put("applicationId", CONFIG_APPKEY);
            retMap.put("sig", sig);
            retMap.put("timestamp", String.valueOf(timestamp));
            retMap.put("alg", CONFIG_ENCRYPTALGORITHM);
        } catch (Exception e) {
            throw new SysException("编译失败!");
        }
        return retMap;
    }
    
    public static String getDigest(String input, String digestMethod) {
        if (null == input) return null;
        try {
            MessageDigest md = MessageDigest.getInstance(digestMethod);
            md.update(input.getBytes());
            byte[] b = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getVerificationJson().toJSONString());
    }
    
}